<template>
    <a-layout>
        <a-layout-header class="header">
            <div class="logo">
                <img v-if="logo" :src="logo" style="width: auto; height: 24px; border-radius: 6px;" />
                <span style="margin-left: 10px;">{{ title }}</span>
            </div>
            <div class="logout" v-if="$store.state.userInfo.userInfo.logined">
                {{ greetings }}，
                <span v-if="userNameField">
                    {{ $store.state.userInfo.userInfo.userNick }}
                    <a-avatar v-if="$store.state.userInfo.userInfo.avatar" :src="`/api${$store.state.userInfo.userInfo.avatar}`" style="margin: 0 8px;" />
                    <a-avatar v-else icon="user" style="margin: 0 8px;" />
                </span>
                <a-button style="margin-left: 8px;" shape="round" @click="logout" size="small" ghost>登出</a-button>
            </div>
            <div class="logout" v-else>
                {{ greetings }} <a-button shape="round" @click="login" size="small" ghost>登录</a-button>
            </div>
        </a-layout-header>
        <a-layout>
            <a-layout-sider width="200" style="background: #fff">
                <a-menu mode="inline" v-model:selectedKeys="$store.state.page.selectedKeys"
                    v-model:openKeys="$store.state.page.openKeys" :style="{ height: '100%', borderRight: 0 }">
                    <template v-for="(menu, index) in filteredMenuList" :key="menu.key">
                        <a-sub-menu v-if="menu.subMenu && menu.subMenu.length > 0" :key="menu.key">
                            <template #title>
                                <span>
                                    <component :is="menu.icon" />
                                    {{ menu.title }}
                                </span>
                            </template>
                            <a-menu-item v-for="(subMenu, subIndex) in menu.subMenu" :key="subMenu.key"
                                @click="navigate(subMenu.target)">
                                <template #icon><component :is="subMenu.icon" /></template>
                                <span>{{ subMenu.title }}</span>
                            </a-menu-item>
                        </a-sub-menu>
                    </template>
                </a-menu>
            </a-layout-sider>
            <a-layout style="padding: 0 24px 24px">
                <a-layout-content :style="{ overflowY: 'auto', background: '#fff', padding: '24px', margin: '16px 0 0 0' }" class="content-layout">
                    <slot></slot>
                </a-layout-content>
            </a-layout>
        </a-layout>
    </a-layout>
</template>
<script>
import {
    UserOutlined,
    LaptopOutlined,
    NotificationOutlined,
    BellOutlined,
    HomeOutlined,
    DeploymentUnitOutlined,
    ControlOutlined
} from "@ant-design/icons-vue";
import { defineComponent, ref, createVNode, computed } from "vue";
import { useRouter } from "vue-router";
import axios from "axios";
import { useStore } from "vuex";
import { Modal, message, Avatar } from "ant-design-vue";
import config from "@/config";
import { checkPermission } from "@/utils/permission";
export default defineComponent({
    components: {
        UserOutlined,
        LaptopOutlined,
        NotificationOutlined,
        BellOutlined,
        HomeOutlined,
        DeploymentUnitOutlined,
        ControlOutlined,
        Avatar
    },
    created() {
        this.greetingsByTime();
    },
    setup() {
        const router = useRouter();
        const store = useStore();
        const greetings = ref("");

        const title = ref(config.SystemTitle);
        const logo = ref(config.SystemLogo);
        const menuList = ref(config.MenuTree);
        const userNameField = ref(config.UserNameField);
        
        // 根据权限过滤菜单
        const filteredMenuList = computed(() => {
            console.log('当前用户权限:', store.state.userInfo.userInfo.permissions);
            
            return menuList.value.map(menu => {
                // 过滤子菜单项
                const filteredSubMenu = menu.subMenu.filter(subMenu => {
                    // 查找对应的路由配置
                    const route = Object.values(config.routes).find(route => 
                        route.name === subMenu.target || 
                        (route.meta && route.meta.subMenuKey === subMenu.key)
                    );
                    
                    // 如果路由没有权限要求，则显示
                    if (!route || !route.meta || !route.meta.permission) {
                        return true;
                    }
                    
                    // 输出调试信息
                    console.log('菜单项:', subMenu.title, '需要权限:', route.meta.permission);
                    
                    // 检查用户是否有权限访问该菜单
                    const hasAuth = checkPermission(route.meta.permission);
                    console.log('菜单项权限检查结果:', subMenu.title, hasAuth);
                    return hasAuth;
                });
                
                // 返回带有过滤后子菜单的菜单项
                return {
                    ...menu,
                    subMenu: filteredSubMenu
                };
            }).filter(menu => menu.subMenu && menu.subMenu.length > 0); // 只显示有子菜单的主菜单
        });

        function navigate(name, key) {
            router.push({ name: name });
        }

        async function logout() {
            try {
                // 调用后端登出接口
                await axios.post('/api/admin/logout');
                
                // 清除本地登录状态
                localStorage.removeItem('token');
                store.dispatch({ type: 'logout' });
                
                // 清除权限缓存
                import('@/directives/permission').then(module => {
                    if (module.clearPermissionCache) {
                        module.clearPermissionCache();
                    }
                });
                
                // 跳转到登录页
                router.push('/login');
                message.success('登出成功');
            } catch (e) {
                console.error('登出失败:', e);
                message.error('登出失败，请稍后重试');
            }
        }

        function login() {
            router.push('/login');
        }

        function greetingsByTime() {
            console.log(store.state);
            const now = new Date();
            const hour = now.getHours();
            if (hour < 6) {
                greetings.value = "凌晨好";
            } else if (hour < 9) {
                greetings.value = "早上好";
            } else if (hour < 12) {
                greetings.value = "上午好";
            } else if (hour < 14) {
                greetings.value = "中午好";
            } else if (hour < 17) {
                greetings.value = "下午好";
            } else if (hour < 19) {
                greetings.value = "傍晚好";
            } else if (hour < 22) {
                greetings.value = "晚上好";
            } else {
                greetings.value = "夜里好";
            }
        }

        return {
            selectedKeys1: ref(["2"]),
            selectedKeys2: ref(["1"]),
            collapsed: ref(false),
            openKeys: ref(["file"]),
            navigate,
            logout,
            login,
            greetings,
            greetingsByTime,

            title,
            logo,
            menuList,
            filteredMenuList,
            userNameField
        };
    },
});
</script>
<style>
#components-layout-demo-top-side-2 .logo {
    float: left;
    width: 120px;
    height: 31px;
    margin: 16px 24px 16px 0;
    background: rgba(255, 255, 255, 0.3);
}

.ant-row-rtl #components-layout-demo-top-side-2 .logo {
    float: right;
    margin: 16px 0 16px 24px;
}

.site-layout-background {
    background: #fff;
}

.content-layout {
    min-height: calc(100vh - 0px);
}

.header {
    display: inline;
    /* align-items: center; */
}

.logo {
    color: white;
    float: left;
    user-select: none;
}

.logout {
    color: white;
    float: right;
}
</style>